package com.adtech.farmProducts.activities.activity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.RelativeLayout;

import com.adtech.common.Common;
import com.adtech.common.http.AsyncHttpPostFormData;
import com.adtech.common.http.AsyncHttpResponse;
import com.adtech.common.http.AsyncOkHttpClient;
import com.adtech.common.http.AsyncResponseHandler;
import com.adtech.common.model.RspModel;
import com.adtech.common.utils.AccountManagers;
import com.adtech.common.utils.SPUtil;
import com.adtech.farmProducts.App;
import com.adtech.farmProducts.IndexActivity;
import com.adtech.farmProducts.R;
import com.adtech.farmProducts.base.BaseActivity;
import com.adtech.farmProducts.base.BaseNfcActivity;
import com.adtech.farmProducts.location.MyLocation;
import com.adtech.farmProducts.model.FUserInfo;
import com.adtech.farmProducts.utils.Constants;
import com.adtech.farmProducts.widget.ClearTextIconEditText;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.gyf.barlibrary.ImmersionBar;

import java.io.IOException;
import java.lang.reflect.Type;

import butterknife.BindView;
import butterknife.OnCheckedChanged;
import butterknife.OnClick;

/**
 * 登录
 */
public class LoginActivity extends BaseNfcActivity {

    @BindView(R.id.root_layout)
    RelativeLayout rootLayout;
    @BindView(R.id.ed_name)
    public ClearTextIconEditText edName;
    @BindView(R.id.ed_pwd)
    public ClearTextIconEditText edPwd;
    @BindView(R.id.ck_remember_pwd)
    public CheckBox cbRememb;
    @BindView(R.id.btn_login)
    Button buttonLogin;
    private boolean rememberPwd;

    @Override
    protected int getLayoutSourceId() {
        return R.layout.activity_login;
    }

    public static void show(Context context) {
        Intent intent = new Intent(context, LoginActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void initImmersionBar() {
        super.initImmersionBar();
        ImmersionBar.with(this)
                .statusBarColor(R.color.trans).init();
    }

    @OnClick({R.id.btn_login, R.id.btn_register})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_login:
                onCheck();
                break;
            case R.id.btn_register:
                RegisterActivity.show(mContext);
                break;
        }
    }

    @Override
    protected void initData() {
        initLocation();
        super.initData();
    }

    @Override
    protected void initWidgets() {
        ImmersionBar.setTitleBar(this, findViewById(R.id.top_view));
    }

    @Override
    public void onResume() {
        edName.setMaxLength(edName, 11, "手机号");
        try {
            cbRememb.setChecked(Boolean.parseBoolean(String.valueOf(SPUtil.get(Common.Static.remember_pwd, false))));
            Object name = SPUtil.get(Common.Static.name_key, "");
            Object pwd = SPUtil.get(Common.Static.pwd_key, "");
            if (name != null) {
                edName.setText(name.toString());
            }
            if (pwd != null) {
                edPwd.setText(pwd.toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        super.onResume();
    }

//    @Override
//    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        if (requestCode == 10) {
//            if (Build.VERSION.SDK_INT >= 23) {
//                if (!Settings.canDrawOverlays(this)) {
//                    // SYSTEM_ALERT_WINDOW permission not granted...
//                    Toast.makeText(LoginActivity.this,"not granted",Toast.LENGTH_SHORT);
//                }
//            }
//        }
//    }

    @OnCheckedChanged({R.id.ck_remember_pwd})
    public void OnCheckedChangeListener(CompoundButton view, boolean isCheck) {
        switch (view.getId()) {
            case R.id.ck_remember_pwd://记住密码
                rememberPwd = isCheck;
                break;
        }
    }

    private void initLocation() {
        MyLocation myLocation = MyLocation.getInstance();
        myLocation.initLocation(getApplicationContext());
        myLocation.startLocation();
    }

    /**
     * 用户名密码判断
     */
    private void onCheck() {
        String valueName = String.valueOf(edName.getText()).trim();
        String valuePwd = String.valueOf(edPwd.getText()).trim();
        if (TextUtils.isEmpty(valueName)) {
            App.getInstance().showMessage(getResources().getString(R.string.message_name));
            return;
        }
        if (TextUtils.isEmpty(valuePwd)) {
            App.getInstance().showMessage(getResources().getString(R.string.message_pwd));
            return;
        }
        if (valuePwd.length() <= 5) {
            App.getInstance().showMessage(getResources().getString(R.string.message_pwd_length));
            return;
        }
        SPUtil.put(Common.Static.remember_pwd, rememberPwd);
        if (rememberPwd) {
            SPUtil.put(Common.Static.name_key, valueName);
            SPUtil.put(Common.Static.pwd_key, valuePwd);
        } else {
            SPUtil.put(Common.Static.pwd_key, "");
        }
        onLogin(valueName, valuePwd);
    }

    /**
     * 用户登录
     *
     * @param phone 用户名
     * @param pwd   密码
     */
    private void onLogin(String phone, String pwd) {
        loadingDialogShow(false);
        AsyncOkHttpClient okHttpClient = new AsyncOkHttpClient();
        AsyncHttpPostFormData asyncHttpPostFormData = new AsyncHttpPostFormData();
        asyncHttpPostFormData.addFormData("mobile", phone);
        asyncHttpPostFormData.addFormData("password", pwd);
        okHttpClient.posts(Common.Constant.API_IP + "user/login", asyncHttpPostFormData, new AsyncResponseHandler() {
            @Override
            public void onFailure(IOException e) {
                onDismiss();
                App.getInstance().showMessage(getResources().getString(R.string.connection_error));
                e.printStackTrace();
            }

            @Override
            public void onSuccess(AsyncHttpResponse response) {
                onDismiss();
                Type type = new TypeToken<RspModel<FUserInfo>>() {
                }.getType();
                RspModel<FUserInfo> rspModel = getAnalysis(response, type, "用户登录");
                if (rspModel == null) {
                    return;
                }
                switch (rspModel.getCode()) {
                    case 1:
                        if (rspModel.getData() != null && !"".equals(rspModel.getData().toString())) {//保存用户
                            FUserInfo userInfo = rspModel.getData();
                            if (userInfo.getToken() != null && !"".equals(userInfo.getToken())) {
                                if (userInfo.getCompanyInfos() != null && !"[]".equals(userInfo.getCompanyInfos().toString())) {
                                    if (userInfo.getCompanyInfos().size() > 1) {
                                        dialogCancel(userInfo);
                                    } else {
                                        userInfo.setInfo(userInfo.getCompanyInfos().get(0));
                                        AccountManagers.login(userInfo.getUserId(), userInfo.getToken(), new Gson().toJson(userInfo),userInfo.getThirdToken());
                                        IndexActivity.show(mContext);
                                        finish();
                                    }
                                    Constants.userType=1;
                                }
                            } else {
                                App.getInstance().showMessage(rspModel.getMessage());
                            }
                        } else {
                            App.getInstance().showMessage(rspModel.getMessage());
                        }
                        break;
                    default:
                        App.getInstance().showMessage(rspModel.getMessage());
                        break;
                }
            }
        });
    }

    /**
     * 显示-多公司选择
     */
    private void dialogCancel(final FUserInfo info) {
        final String[] cancelReason = new String[info.getCompanyInfos().size()];
        for (int i = 0; i < info.getCompanyInfos().size(); i++) {
            cancelReason[i] = info.getCompanyInfos().get(i).getCompanyName();
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle("请登录选择公司");
        builder.setItems(cancelReason, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                info.setInfo(info.getCompanyInfos().get(0));
                AccountManagers.login(info.getUserId(), info.getToken(), new Gson().toJson(info),info.getThirdToken());
                IndexActivity.show(mContext);
                finish();
            }
        });
        builder.setPositiveButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.show();
    }
}
